package org.lanettiesso.dubbo.simple.schema;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;

public class SimpleDubboBeanDefinitionParser implements BeanDefinitionParser {

    private Class<?> clazz;

    public SimpleDubboBeanDefinitionParser(Class<?> clazz) {
        this.clazz = clazz;
    }

    @Override
    public BeanDefinition parse(Element element, ParserContext parserContext) {
        RootBeanDefinition beanDefinition = new RootBeanDefinition();
        beanDefinition.setBeanClass(clazz);
        beanDefinition.setLazyInit(false);
        parserContext.getRegistry().registerBeanDefinition(clazz.getSimpleName(), beanDefinition);

        String tagName = element.getLocalName();
        switch (tagName) {
            case "application":
                String appName = element.getAttribute("name");
                beanDefinition.getPropertyValues().add("name", appName);
                break;
            case "protocol":
                String protocolName = element.getAttribute("name");
                String port = element.getAttribute("port");
                beanDefinition.getPropertyValues().add("name", protocolName);
                beanDefinition.getPropertyValues().add("port", port);
                break;
            case "registry":
                String address = element.getAttribute("address");
                beanDefinition.getPropertyValues().add("address", address);
                break;
        }
        return beanDefinition;
    }
}
